/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2009, Around(J2)ME				                                 **
 **   All rights reserved.                                                   **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the New BSD License which accompanies this    			 **
 **   distribution.											                 **
 **   A copy is found in the textfile LICENSE.txt							 **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Main developers:                                                       **
 **     Juri Strumpflohner		http://blog.js-development.com	             **
 **		Matthias Braunhofer		http://matthias.jimdo.com                    **
 **                                                                          **
 **  **********************************************************************  */

package com.aroundj2me.model;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.HttpConnection;

import com.aroundj2me.utility.StringReplacer;

public class GMapsGeocoder extends AbstractHTTPCommunicator {
	private ProgressListener progListener;
	//{0}=address, {1}=city
	private String geocodingBaseURL = "http://maps.google.com/maps/geo?q=";
	private String geocodingURLlastPiece = "&output=xml&oe=utf8&sensor=true_or_false&key=ABQIAAAA008FGL6WDtMr2ELm_3UvGhTwa4JwLYAJxmob2w5Mp9c8CPT1rhSsiywOo4EgCXUaUvmkobVaRrsbrw";
	
	public GMapsGeocoder(String address, String city) {
		
		address = new StringReplacer().replace(address, " ", "%20");
		
		StringBuffer connectionString = new StringBuffer();
		connectionString.append(geocodingBaseURL);
		connectionString.append(address);
		connectionString.append(",");
		connectionString.append(city);
		connectionString.append(geocodingURLlastPiece);
		this.connectionURL = connectionString.toString();
	}
	
//    private static String getGeocodeError(int errorCode) { 
//        switch (errorCode) { 
//        case 400: 
//            return "Bad request"; 
//        case 500: 
//            return "Server error"; 
//        case 601: 
//            return "Missing query"; 
//        case 602: 
//            return "Unknown address"; 
//        case 603: 
//            return "Unavailable address"; 
//        case 604: 
//            return "Unknown directions"; 
//        case 610: 
//            return "Bad API key"; 
//        case 620: 
//            return "Too many queries"; 
//        default: 
//            return "Generic error"; 
//        } 
//    } 

	
	
	public void run() {		
		this.statusMessage = "";
		
		HttpConnection hc = null;
		InputStream in = null;
		if(progListener!=null) progListener.incrementProgress();
		try{
			hc = createConnection(HttpConnection.GET);
			
			if(progListener!=null) progListener.incrementProgress();
			
			if(hc.getResponseCode() == HttpConnection.HTTP_OK){
				in = hc.openInputStream();
				
				byte[] data = null;
				int length = (int)hc.getLength();
				if (length > 0) {
	                int bytesread = 0;
	                data = new byte[length];
	                for (int offset = 0; offset < length;
	                     offset += bytesread) {
	                     bytesread = in.read(data, offset, length-bytesread);
	                }
				}else{
					ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
                    byte[] buffer = new byte[512]; 
                    int count; 
                    while ( (count = in.read(buffer)) >= 0 ) { 
                        bos.write(buffer, 0, count); 
                    } 
                    data = bos.toByteArray(); 
				}
				
				if(progListener!=null) progListener.incrementProgress();
				
				response = new String(data);
			}else{
				response = null;
				statusMessage = "The connection with the server failed! Please retry again.";
			}
		}catch (SecurityException e) {
			statusMessage = "The process has been aborted by the user!";
		}catch (Exception e) {
			statusMessage = "The connection with the server failed! Please retry again.";
		}finally{
			try{
				if(in != null) in.close();
				if(hc != null) hc.close();
			}catch(IOException ioe){}
			if(progListener!=null) progListener.incrementProgress();
			notifyListener();
		}
	}
}
